package com.yami.shop.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.yami.shop.app.utils.HttpResult;
import com.yami.shop.app.utils.ResultCodeEnum;
import com.yami.shop.bean.cashregisterapp.AppCashRegisterSystemUser;
import com.yami.shop.bean.model.Order;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yami.shop.service.AppCashRegisterSystemUserService;
import com.yami.shop.bean.model.LoginHist;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.yami.shop.service.AppLoginHistService;
import com.yami.shop.app.dto.ShiftStatisticsDto;
import com.yami.shop.bean.cashregisterapp.AppTransactionRefund;
import com.yami.shop.service.AppTransactionRefundService;
import com.yami.shop.bean.model.UserDeposit;
import com.yami.shop.service.UserDepositService;

@RestController
@RequestMapping("/app/appCashRegisterSystemUser")
@Api(tags="收银系统用户接口")
public class AppCashRegisterSystemUserController {


    @Autowired
    private AppCashRegisterSystemUserService appCashRegisterSystemUserService;
    @Autowired
    private AppLoginHistService appLoginHistService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AppTransactionRefundService appTransactionRefundService;
    @Autowired
    private UserDepositService userDepositService;

    /**
     * 查看收银机用户接口
     */
    @GetMapping("/getAppCashRegisterSystemUserList")
    public HttpResult checkDelivery(){
        List<AppCashRegisterSystemUser> appCashRegisterSystemUserList = appCashRegisterSystemUserService.list();
        return HttpResult.success(appCashRegisterSystemUserList);
    }

    @PostMapping("/getAppCashRegisterSystemUser")
    public HttpResult getAppCashRegisterSystemUser(){
        AppCashRegisterSystemUser appCashRegisterSystemUser = appCashRegisterSystemUserService.getById(SecurityUtils.getSysUser().getUserId());
        return HttpResult.success(appCashRegisterSystemUser);
    }

    @PostMapping("/addAppCashRegisterSystemUser")
    @ApiOperation(value = "添加收银系统用户",notes = "添加")
    public HttpResult addAppCashRegisterSystemUser(AppCashRegisterSystemUser appCashRegisterSystemUser){
        appCashRegisterSystemUser.setCreateTime(new Date());
        appCashRegisterSystemUserService.save(appCashRegisterSystemUser);
        return HttpResult.success(appCashRegisterSystemUser);
    }

    @PostMapping("/deleteAppCashRegisterSystemUser")
    @ApiOperation(value = "删除收银系统用户",notes="删除")
    public HttpResult deleteAppCashRegisterSystemUser(String ids){
        String[] idsString = ids.split(",",-1);
        List<Long> idsLong = new ArrayList<>();
        for(String id : idsString){
            idsLong.add(Long.valueOf(id));
        }
        appCashRegisterSystemUserService.deleteCashRegisterSystemUserByIds(idsLong);
        return HttpResult.success();
    }

    //修改密码之前要校验密码
    @PostMapping("/checkPassword")
    public HttpResult checkPassword(Long userId,Long shopId,String name,String oldPassword){
        AppCashRegisterSystemUser appCashRegisterSystemUser = new AppCashRegisterSystemUser();
        appCashRegisterSystemUser.setUserId(userId);
        appCashRegisterSystemUser.setShopId(shopId);
        appCashRegisterSystemUser.setName(name);
        appCashRegisterSystemUser.setPassword(oldPassword);
        AppCashRegisterSystemUser appCashRegisterSystemUser1 = appCashRegisterSystemUserService.checkUserPassword(appCashRegisterSystemUser);
        if(appCashRegisterSystemUser1 != null){
            return HttpResult.success();
        }
        return HttpResult.failure(ResultCodeEnum.CHECK_FAIL);
    }


    //收银系统用户修改密码
    @PostMapping("/updatePassword")
    public HttpResult updatePassword(Long userId,Long shopId,String name,String newPassword){
        AppCashRegisterSystemUser appCashRegisterSystemUser = new AppCashRegisterSystemUser();
        appCashRegisterSystemUser.setUserId(userId);
        appCashRegisterSystemUser.setShopId(shopId);
        appCashRegisterSystemUser.setName(name);
        appCashRegisterSystemUser.setPassword(newPassword);
        int result = appCashRegisterSystemUserService.updateUserPassword(appCashRegisterSystemUser);
        if(result >0){
            return HttpResult.success();
        }
        return HttpResult.failure("修改密码失败");
    }

    /**
     * 判断电话是否重复
     */
    @GetMapping("/checkPhone")
    public HttpResult checkPhone(String mobile){
        AppCashRegisterSystemUser appCashRegisterSystemUser = appCashRegisterSystemUserService.getUserByPhone(mobile);
        return HttpResult.success(appCashRegisterSystemUser);
    }

    /**
     * 收银员交接班统计
     * */
    @PostMapping("/userShiftStatistics")
    public HttpResult userShiftStatistics(){
        Long userId = SecurityUtils.getSysUser().getUserId();
        Long shopId = SecurityUtils.getSysUser().getShopId();
        ShiftStatisticsDto shiftStatisticsDto = new ShiftStatisticsDto();
        BigDecimal totalSales = new BigDecimal("0.00");//总销售额
        BigDecimal cashSales = new BigDecimal("0.00");//现金收款总额
        BigDecimal umsPaySales = new BigDecimal("0.00");//线上支付收款总额
        BigDecimal accountSales = new BigDecimal("0.00");//余额支付收款总额
        BigDecimal oldAccountPay = new BigDecimal("0.00");//老账户支付总额
        //成交笔数
        Integer dealCount=0;
        //现金笔数
        Integer cashCount=0;
        //网络笔数
        Integer umsCount=0;
        List<LoginHist> loginHists = appLoginHistService.getLoginHist(userId);
        List<Order> orders = new ArrayList<>();
        List<UserDeposit> userDeposits;
        if(CollectionUtils.isNotEmpty(loginHists)){
            LoginHist loginHist = loginHists.get(0);
            shiftStatisticsDto.setLoginTime(loginHist.getLoginTime());
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cashier",userId)
                        .eq("shop_id",shopId)
                        .eq("status",5)
                        .ge("create_time",loginHist.getLoginTime());
            List<Order> orderList = orderService.list(queryWrapper);
            if(CollectionUtils.isNotEmpty(orderList)){
                for(Order order : orderList){
                    //正常订单
                    if(order.getOrderState()!=1){
                        if(order.getOldAccountPay()!=null){
                            oldAccountPay =  oldAccountPay.add(order.getOldAccountPay());
                        }
                        //orderList.add(order);
                        dealCount++;
                        totalSales=totalSales.add(new BigDecimal(order.getActualTotal())).setScale(2,BigDecimal.ROUND_HALF_UP);
                        //支付方式 0 现金支付 1 微信支付 2 银联支付 3 账户余额支付
                        if(null!=order.getPayType()) {
                            if (order.getPayType() == 0) {
                                cashCount++;
                                cashSales = cashSales.add(new BigDecimal(order.getActualTotal())).setScale(2, BigDecimal.ROUND_HALF_UP);
                            } else if (order.getPayType() == 2) {
                                umsCount++;
                                umsPaySales = umsPaySales.add(new BigDecimal(order.getActualTotal()));
                            } else if (order.getPayType() == 3) {
                                accountSales = accountSales.add(new BigDecimal(order.getActualTotal()));
                            }
                        }
                    }
                    else{//撤销订单
                    }
                }
                shiftStatisticsDto.setDealCount(dealCount);
                shiftStatisticsDto.setCashCount(cashCount);
                shiftStatisticsDto.setUmsCount(umsCount);
            }
            shiftStatisticsDto.setTotalSales(totalSales);
            shiftStatisticsDto.setCashSales(cashSales);
            shiftStatisticsDto.setUmsPaySales(umsPaySales);
            shiftStatisticsDto.setAccountSales(accountSales);
            shiftStatisticsDto.setOldAccountPay(oldAccountPay);
            //封装退款统计数据
            BigDecimal appTransactionRefundAmount = new BigDecimal("0.00");//退款总额
            BigDecimal appTransactionRefundCashAmount = new BigDecimal("0.00");//现金退款总额
            BigDecimal appTransactionRefundUmsAmount = new BigDecimal("0.00");//网络退款
            Integer appTransactionRefundCount=0;//退款单数
            Integer appTransactionRefundCashCount=0;//现金笔数
            Integer appTransactionRefundUmsCount=0;//网络笔数
            QueryWrapper<AppTransactionRefund> qw = new QueryWrapper<>();
            qw.eq("user_id",userId)
              .eq("shop_id",shopId)
              .ge("create_time",loginHist.getLoginTime());
            List<AppTransactionRefund> appTransactionRefunds  = appTransactionRefundService.list(qw);
            if(CollectionUtils.isNotEmpty(appTransactionRefunds)){
                for(AppTransactionRefund appTransactionRefund:appTransactionRefunds){
                    appTransactionRefundCount++;
                    appTransactionRefundAmount = appTransactionRefundAmount.add(new BigDecimal(appTransactionRefund.getAmount()/100));
                    Order order  = orderService.getOrderByOrderNumber(appTransactionRefund.getMerchantOrderId().toString());
                    if(order.getPayType()==0){
                        //现金支付
                        appTransactionRefundCashAmount = appTransactionRefundCashAmount.add(new BigDecimal(appTransactionRefund.getAmount()/100));
                        appTransactionRefundCashCount++;
                    }else if(order.getPayType()==2){
                        //银联支付
                        appTransactionRefundUmsAmount = appTransactionRefundUmsAmount.add(new BigDecimal(appTransactionRefund.getAmount()/100));
                        appTransactionRefundUmsCount++;
                    }
                }
            }
            shiftStatisticsDto.setAppTransactionRefundAmount(appTransactionRefundAmount);
            shiftStatisticsDto.setAppTransactionRefundCashAmount(appTransactionRefundCashAmount);
            shiftStatisticsDto.setAppTransactionRefundUmsAmount(appTransactionRefundUmsAmount);
            shiftStatisticsDto.setAppTransactionRefundCount(appTransactionRefundCount);
            shiftStatisticsDto.setAppTransactionRefundCashCount(appTransactionRefundCashCount);
            shiftStatisticsDto.setAppTransactionRefundUmsCount(appTransactionRefundUmsCount);
            shiftStatisticsDto.setAppTransactionRefunds(appTransactionRefunds);
            shiftStatisticsDto.setOrders(orders);

            //封装充值统计数据
            QueryWrapper<UserDeposit> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id",userId)
                         .eq("shop_id",shopId)
                         .ge("create_time",loginHist.getLoginTime());
            userDeposits = userDepositService.list(queryWrapper1);
            shiftStatisticsDto.setUserDeposits(userDeposits);
            //充值金额
            BigDecimal userDepositAmount = new BigDecimal("0.00");
            //充值笔数
            Integer userDepositCount=0;
            if(CollectionUtils.isNotEmpty(userDeposits)){
                for(UserDeposit userDeposit:userDeposits){
                    userDepositCount++;
                    userDepositAmount = userDepositAmount.add(new BigDecimal(userDeposit.getAmount()));
                }
            }
            shiftStatisticsDto.setUserDepositAmount(userDepositAmount);
            shiftStatisticsDto.setUserDepositCount(userDepositCount);
            return HttpResult.success(shiftStatisticsDto);
        }else{
            return HttpResult.failure("没有登陆记录");
        }
    }


}
